//
//  NetworkTools.swift
//  AFN封装swift
//
//  Created by celeste on 16/5/17.
//  Copyright © 2016年 celeste. All rights reserved.
//

import UIKit
import AFNetworking
enum LDRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    // MARK : - 应用程序信息
    let appkey = "1394568027"
    let appSecret = "b7594481db659959f517519686de4917"
    let redirectUri = "http://www.baidu.com"
    
    
    //单例
    static let sharedTools :NetworkTools = {
        let tools = NetworkTools(baseURL: nil)
        
        //设置反序列化支持数据格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    func request(method: LDRequestMethod, URLString: String, parameter: [String: AnyObject]?, finished: (result: [String: AnyObject]?)->()) {
        
        //成功回调
        let success = { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
            
            if let result = responseObject as? [String: AnyObject] {
                finished(result: result)
            }else{
                
                print("数据格式错误")
                finished(result: nil)
            }
        }
        //失败回调
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            print("网络请求错误\(error)")
            finished(result: nil)
        }
        
        if method == .GET {
            GET(URLString, parameters: parameter, progress: nil, success: success, failure: failure)
            
        }else{
            POST(URLString, parameters: parameter, progress: nil, success: success, failure: failure)
        }

    }
    
}

